# -*- coding:utf-8 -*-
import codecs
from json import dumps, loads
from logger_utility.loggconfig import getLogger

logger = getLogger("JsonIO")


def load_file(path, error='ignore'):
    """
    通过JOSN读取
    :param path:
    :return:
    """
    ret = []
    if os.path.exists(path):
        with codecs.open(path, encoding='utf8') as fi:
            for line in fi:
                line = line.strip()
                if not line:
                    continue
                try:
                    _ = loads(line)
                    ret.append(_)

                except Exception as e:
                    if error != 'ignore':
                        raise

        logger.info("Load Data Path(%s) Length(%s)", path, len(ret))
    else:
        logger.info("Load Data Path(%s) Not Exists", path)
    return ret


def dump_file(data, path):
    """
    将内容进行dumps
    :param path:
    :return:
    """
    with codecs.open(path, 'w', encoding='utf8') as fo:
        for line in data:
            str_ = dumps(line, ensure_ascii=False)
            fo.write(str_)
            fo.write('\n')